<template>
  <div
    ref="contentRefDom"
    class="flex-1 h-full overflow-y-auto flex flex-col justify-between duration-900 dark:bg-zinc-900 dark:text-gray-100 bg-gray-50"
  >
    <p class="text-sm text-gray-500"></p>
    <div
      v-for="item in userMessageRecord"
      :key="item.id"
      class="flex-1 p-4 space-y-2"
    >
      <template v-if="item.sender === 'robot'">
        <div class="flex relative items-center space-x-2 cursor-pointer">
          <My-svg-icon
            name="OpenAi"
            class="w-5 h-5 absolute left-[-30px] top-0"
          ></My-svg-icon>

          <div
            class="bg-white w-full rounded-sm shadow-md ml-[30px] duration-900 dark:bg-zinc-300 dark:text-gray-100 text-gray-300 text-sm"
          >
            <MdPreview
              :theme="useThemeStore.currentTheme.theme"
              :editorId="id"
              :modelValue="item.content"
            />
            <MdCatalog :editorId="id" :scrollElement="scrollElement" />
          </div>
        </div>
      </template>
      <template v-else>
        <div class="flex items-start space-x-2 justify-end">
          <div
            class="bg-blue-500 text-white p-2 dark:bg-zinc-800 dark:text-gray-100 rounded-sm shadow-md max-w-xs text-sm"
          >
            {{ item.content }}
          </div>
        </div>
      </template>
    </div>
    <template v-if="isRender">
      <div
        class="flex items-center p-2 space-x-2 hover:bg-blue-200 cursor-pointer"
      >
        <My-svg-icon
          name="OpenAi"
          class="w-5 h-5 absolute left-0 top-0"
        ></My-svg-icon>
        <div
          class="bg-white w-full rounded-sm shadow-md ml-[30px] dark:bg-zinc-900 dark:text-gray-100 text-gray-900 text-sm"
        >
          <MdPreview
            :theme="useThemeStore.currentTheme.theme"
            :editorId="id"
            :modelValue="currentMessage"
          />
        </div>
      </div>
    </template>
    <div class="flex w-full bottom-1 items-center rounded-sm shadow-md">
      <input
        type="text"
        v-model="inputMessage"
        placeholder="Type a message"
        class="flex-1 px-3 py-1 rounded-sm outline-none dark:text-gray-100 dark:bg-zinc-900 text-gray-800 text-sm"
      />
      <button
        v-if="!isRender"
        @click="sendMessage"
        :disabled="isRender"
        class="bg-blue-500 dark:bg-blue-700 dark:text-gray-100 text-white px-3 py-1 rounded-sm ml-2 hover:bg-blue-600 transition duration-150 text-sm"
      >
        Send
      </button>
      <button
        v-else
        :disabled="isRender"
        class="bg-gray-400 dark:text-whitedark:bg-blue-300 text-white px-3 py-1 rounded-sm ml-2 transition duration-150 text-sm"
      >
        Send
      </button>
    </div>
  </div>
</template>
<script setup>
import 'md-editor-v3/lib/style.css'
import { io } from 'socket.io-client'
import { timestamp, useScroll } from '@vueuse/core'
import { MdPreview, MdCatalog } from 'md-editor-v3'
import useTheme from '@/store/theme/index.js'
import { ref, onBeforeUnmount, onMounted, nextTick } from 'vue'
const useThemeStore = useTheme()
const id = 'preview-only'
const scrollElement = document.documentElement
const userMessageRecord = JSON.parse(
  window.localStorage.getItem('userMessageRecord')
)
  ? ref(JSON.parse(window.localStorage.getItem('userMessageRecord')))
  : ref([
      {
        id: Date.now(),
        sender: 'robot',
        content: '你好我是站内大模型,你可以向我发起提问!',
        timestamp: new Date().toISOString()
      }
    ])
const inputMessage = ref('')
const socket = io(import.meta.env.VITE_API_BASE_URL)
const MAX_MESSAGES = 100 // 最大消息数量
let currentMessage = ref('')
let isRender = ref(false)
// 创建消息对象
const createMessage = (sender, content) => ({
  id: Date.now(), // 用时间戳生成唯一 ID
  sender,
  content,
  timestamp: new Date().toISOString()
})
// 发送消息
const sendMessage = () => {
  ScrollToBottom()
  if (inputMessage.value) {
    const message = createMessage('user', inputMessage.value)
    userMessageRecord.value.push(message)
    socket.emit('sendMessage', message)
    inputMessage.value = ''
  }
}
//滚动到底部
const contentRefDom = ref(null)
const ScrollToBottom = (addHeight) => {
  const { y } = useScroll(contentRefDom.value, { behavior: 'smooth' })
  const contentHeight = contentRefDom.value.scrollHeight
  y.value = addHeight ? contentHeight + addHeight : contentHeight
}
// 接收消息流
socket.on('receiveMessage', (msg) => {
  ScrollToBottom()
  currentMessage.value += msg
  isRender.value = true
})
// 结束接收消息流
socket.on('dataEnd', () => {
  const message = createMessage('robot', currentMessage.value, false)
  if (userMessageRecord.value.length > MAX_MESSAGES) {
    userMessageRecord.value.shift()
  }
  userMessageRecord.value.push(message)
  window.localStorage.setItem(
    'userMessageRecord',
    JSON.stringify(userMessageRecord.value)
  )
  currentMessage.value = ''
  isRender.value = false
})
// 组件卸载时关闭 socket 连接
onBeforeUnmount(() => {
  socket.disconnect()
})
onMounted(async () => {
  socket.on('error', (errorMessage) => {
    console.error(errorMessage)
  })
  ScrollToBottom()
})
</script>

<style scoped>
/* Optional styling for scrollbar */
::-webkit-scrollbar {
  width: 8px;
}
::-webkit-scrollbar-thumb {
  background-color: #cfd2d6;
  border-radius: 4px;
}
</style>
